// pages/family/edit/edit.js
const app = getApp();
const util = require('../../../../utils/util.js');
const md5 = require('../../../../utils/md5.js');
const call = require('../../../../utils/request.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: '',
    memberInfoId: '',
    familyDefaultHeadList: [],
    identityList: [],
    mxb: [],
    kwph: [],
    pictureUrl: '',
    identity: 0,
    sex: '1',
    labelInfoList: {},
    // date: '2016-09-01',
    date: util.dataFormat().time1,
    nickname: '',
    height: '',
    weight: '',
    groupId: '',
    isOpenCode: false,
    member: {}
  },
  // 头像选择
  onChooseHead(e) {
    this.setData({
      pictureUrl: e.currentTarget.dataset.pictureUrl
    })
  },
  // 标签选择
  onActive(e) {
    const label = e.currentTarget.dataset;
    let arr = [];
    if (label.type !== 'identity') {
      arr = (label.type === 'mxb' ? this.data.mxb : this.data.kwph).slice();
      arr.indexOf(label.item) > -1 ? arr.splice(arr.indexOf(label.item), 1) : arr.push(label.item); //将新的标签加入到已选标签列表
    }
    this.setData({
      [label.type]: label.type === 'identity' ? label.index : arr
    })
  },
  /**
   * 性别
   */
  radioChange(e) {
    this.setData({
      sex: e.detail.value
    })
  },
  /**
   * 生日
   */
  bindDateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },
  /**
   *  身高体重
   */
  subBody(e) {
    this.setData({
      [e.currentTarget.dataset.type]: e.detail.value
    })
  },
  /**
   * 删除成员开关
   */
  delMember() {
    this.setData({
      isOpenCode: !this.data.isOpenCode
    })
  },
  /**
   * 12)群主更新成员信息
   */
  updateMember() {
    let that = this;
    const url = `/service/standard/v1/family/group/updateMember?access_token=${app.globalData.access_token}`;
    const params = {
      "header": app.globalData.reqHeader,
      "data": {
        "operateUserId": that.data.userId,
        "memberInfoId": that.data.memberInfoId,
        "identityName": that.data.identityList[that.data.identity],
        "nickName": that.data.nickname,
        "sex": that.data.sex,
        "height": that.data.height,
        "birthday": new Date(that.data.date.replace(/-/g, '/')),
        "weight": that.data.weight,
        "headImgUrl": that.data.pictureUrl,
        "memberLabelInfo": {
          "mxb": that.data.mxb,
          "kwph": that.data.kwph
        }
      }
    };
    call.postData(url, params,
      res => {
        console.log('_updateMember_success', res, params);
        if (res.errormsg !== 'success') {
          wx.showToast({
            title: res.errormsg,
            icon: 'none'
          })
        } else {
          that._backMember('修改成员信息成功')
        }
      },
      err => {
        console.log('_updateMember_fail', err);
        wx.showToast({
          title: '网络好像开小差了',
          icon: 'none'
        })
      }, 'api')
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    let optionsArr = (options.addInfo || '').split(','); //页面传递的参数
    let allRequire = [this._getFamilyDefaultHeadList(), this._getIdentityList(), this._getLabelInfoList()]; //所有一部请求
    Promise.all(allRequire).then(res => {
      that.setData({
        userId: optionsArr[0] || '',
        groupId: optionsArr[1] || '',
        familyDefaultHeadList: res[0],
        identityList: res[1],
        labelInfoList: res[2]
      });
      !options.addInfo && that._inherutPage(); //如果是编辑，就获取上一个页面的数据
    })
  },
  _inherutPage() {
    const data = getCurrentPages()[getCurrentPages().length - 2].data; //获取上一页的data
    const member = data.memberList[data.memberIndex]; //获取上一页的成员信息
    console.log('当前成员：', member);
    //设置数据
    this.setData({
      pictureUrl: member.headImgUrl ? member.headImgUrl : '',
      userId: data.userId,
      memberInfoId: member.memberInfoId,
      nickname: member.nickName ? member.nickName : '',
      identity: member.identityName ? this.data.identityList.indexOf(member.identityName) : 0,
      sex: member.sex ? member.sex : 1,
      date: member.birthday ? new Date(parseInt(member.birthday)).Format("yyyy-MM-dd") : util.dataFormat().time1,
      height: member.height ? member.height : '',
      weight: member.weight ? member.weight : '',
      mxb: member.memberLabelInfo ? member.memberLabelInfo.mxb : [],
      kwph: member.memberLabelInfo ? member.memberLabelInfo.kwph : []
    })
  },
  /**
   * 获取验证码
   */
  subCode(e) {
    let that = this;
    const delmember = {
      userId: Number(that.data.userId),
      memberInfoId: Number(that.data.memberInfoId),
      securityCode: String(e.detail.mobileCode),
      securityCellphone: app.globalData.phoneNumber
    }
    console.log('删除信息', delmember)
    this._deleteMember(delmember)
  },
  /**
   * 查询家庭中心的默认头像列表
   */
  _getFamilyDefaultHeadList() {
    const url = `/service/app/v1/account/getFamilyDefaultHeadList?access_token=${app.globalData.access_token}`;
    const params = {
      "header": app.globalData.reqHeader,
      "data": ""
    }
    return new Promise(resolve => {
      call.postData(url, params,
        res => {
          console.log('_getFamilyDefaultHeadList_success', res);
          resolve(res.data)
        },
        err => {
          console.log('_getFamilyDefaultHeadList_fail', err)
        })
    });
  },
  /**
   * 44)查询家庭中心系统预设的身份列表信息
   */
  _getIdentityList() {
    const url = `/service/app/v1/family/group/getIdentityList?access_token=${app.globalData.access_token}`;
    const params = {
      "header": app.globalData.reqHeader,
      "data": {}
    }
    return new Promise((resolve, reject) => {
      call.postData(url, params,
        res => {
          console.log('_getIdentityList_success', res);
          resolve(res.data)
        },
        err => {
          console.log('_getIdentityList_fail', err)
        })
    });
  },
  /**
   * 45)查询家庭中心系统预设的成员标签列表信息
   */
  _getLabelInfoList() {
    const url = `/service/app/v1/family/group/getLabelInfoList?access_token=${app.globalData.access_token}`;
    const params = {
      "header": app.globalData.reqHeader,
      "data": {}
    };
    return new Promise(resolve => {
      call.postData(url, params,
        res => {
          console.log('_getLabelInfoList_success', res);
          resolve(res.data)
        },
        err => {
          console.log('_getLabelInfoList_fail', err)
        })
    });
  },
  /**
   * 10)群主添加家庭成员
   */
  addMember() {
    let that = this;
    const url = `/service/standard/v1/family/group/addMember?access_token=${app.globalData.access_token}`;
    const params = {
      "header": app.globalData.reqHeader,
      "data": {
        "operateUserId": this.data.userId,
        "groupId": this.data.groupId,
        "identityName": this.data.identityList[this.data.identity],
        "nickName": this.data.nickname,
        "birthday": new Date(this.data.date.replace(/-/g, '/')),
        "headImgUrl": this.data.pictureUrl,
        "sex": this.data.sex,
        "height": Number(this.data.height),
        "weight": Number(this.data.weight),
        "memberLabelInfo": {
          "mxb": this.data.mxb,
          "kwph": this.data.kwph
        },
        "faceIdState": true,
        "remoteControlState": false,
        "sprotRecordState": false
      }
    };
    console.log('调试接口', JSON.stringify(params))
    call.postData(url, params,
      res => {
        console.log('_addMember_success', res);
        if (res.errormsg !== 'success') {
          wx.showToast({
            title: res.errormsg,
            icon: 'none'
          })
        } else {
          that._backMember('添加成员成功')
        }
      },
      err => {
        console.log('_addMember_fail', err);
        wx.showToast({
          title: '网络好像出小差了',
          icon: 'none'
        });
      }, 'api');
  },
  /**
   * 11)群主删除家庭成员
   */
  _deleteMember(delmember) {
    var that = this;
    const url = `/service/standard/v1/family/group/deleteMember?access_token=${app.globalData.access_token}`;
    const params = {
      "header": app.globalData.reqHeader,
      "data": delmember
    };
    call.postData(url, params,
      res => {
        console.log('_deleteMember_success', res);
        if (res.errormsg !== 'success') {
          wx.showToast({
            title: res.errormsg,
            icon: 'none'
          })
        } else {
          that._backMember('删除成员成功！');
        }
      },
      err => {
        console.log('_deleteMember_success', err);
        wx.showToast({
          title: '网络好像出小差了',
          icon: 'none'
        })
      }, 'api');
  },
  _backMember(msg) {
    // wx.redirectTo({
    //   url: '/pages/family/member/member',
    //   success() {
    //     wx.showToast({
    //       title: msg,
    //     })
    //   }
    // })
    wx.navigateBack({
      delta: 1,
      success() {
        wx.showToast({
          title: msg,
        })
      }
    })
  }
})